package org.ouwh.fw.model.data;

import org.ouwh.fw.model.AbstractLoader;
import org.ouwh.fw.util.xml.Node;

public class DataLoader extends AbstractLoader {

	private static final String LINK_ID = "link-id";
	private static final String LINK_DATA = "link-data";
	private static final String LIST = "list";
	private static final String STRUCT = "struct";
	private static final String DATA = "data";
	private boolean isInstanceFromClass;

	public DataLoader(Class<?> clazz) throws Exception {
		super("/" + clazz.getName().replaceAll("\\.", "/") + ".mdl");
		isInstanceFromClass = true;
	}

	public DataLoader() {
		isInstanceFromClass = false;
	}

	public Object loadObjecFromNode(Node node) throws Exception {
		Data o = getData(node.getXmlType());
		o.init(node);
		Node[] children = node.getChildren();
		int childrenSize = children.length;
		for (int i = 0; i < childrenSize; i++) {
			Node child = children[i];
			String childName = child.getXmlType();
			// Node Data link-data
			if (childName.equals(LINK_DATA) && isInstanceFromClass) {
				String dataId = child.getXmlAttr(LINK_ID).toString();
				o.addData((Data) loadObjectByName(dataId));
			} else {
				o.addData((Data) loadObjecFromNode(child));
			}
		}
		return o;
	}

	private Data getData(String classType) throws Exception {
		if (classType.equals(DATA)) {
			return new Data();
		} else if (classType.equals(STRUCT)) {
			return new Struct();
		} else if (classType.equals(LIST)) {
			return new List();
		}
		throw new Exception("No correspond class associate with tag[" + classType + "]");
	}

}
